const dbUtil = require('../util/dbutil')
const { genToken } = require('../util/jwt')
const { AssertUtils, RandomUtils } = require('../util/utils')
const { getUserByPhone } = require('./user')
const dayjs = require('dayjs')
/**
 * 发送验证码
 * @param {string} phone 手机
 * @returns 
 */
const sendCode = async (phone) => {
    let user = await getUserByPhone(phone)
    AssertUtils.ObjectNotEmpty(user, "用户不存在")
    let count = await dbUtil.getCount("select count(1) from sms_code where phone = ? and expire_time > ? and status = 0", [phone, dayjs().subtract(1, 'minute').toDate()])
    AssertUtils.isFalse(count > 0, "请勿频繁发送")
    let code = `${RandomUtils.randomNumber(6)}`
    let expire_time = dayjs().add(1, 'minute').toDate()
    await dbUtil.exec("insert into sms_code (phone,code,expire_time) values(?,?,?)", [phone, code, expire_time])
    return code
}

module.exports = {
    sendCode,
}